package com.gzhryc.shared_device.iot.core.hryc;

import com.gzhryc.shared_device.iot.core.IOTClient;
import com.gzhryc.shared_device.iot.core.IOTClientEvent;
import com.gzhryc.shared_device.iot.core.IOTMessage;
import com.gzhryc.shared_device.iot.core.enums.EIOTDeviceState;
import com.gzhryc.socket.SocketEvent;
import com.gzhryc.socket.message.MqttSocketMessage;
import org.apache.commons.lang3.StringUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class HRYCSmartClientEvent implements IOTClientEvent {
	
	static Pattern pat = Pattern.compile("^/[^/]*/([^/]*)/.*$");
	
	final IOTClient client;
	final SocketEvent event;
	
	MqttSocketMessage mqttMsg;
	String deviceSn;

	public HRYCSmartClientEvent(IOTClient client, SocketEvent event) {
		this.client = client;
		this.event = event;
		this.mqttMsg = event.getMessage(MqttSocketMessage.class);
	}

	public void setMqttMsg(MqttSocketMessage mqttMsg) {
		this.mqttMsg = mqttMsg;
	}

	@Override
	public <T extends IOTMessage> T getMessage(Class<T> clazz) {
		if(mqttMsg != null) {
			try {
				T msg = clazz.newInstance();
				msg.setBytes(mqttMsg.getBytes());
				msg.setDeviceSn(getDeviceSn());
				msg.setTopic(mqttMsg.getTopic());
				return msg;
			} catch (InstantiationException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	@Override
	public IOTClient getClient() {
		return client;
	}

	@Override
	public IOTMessage getMessage() {
		if(mqttMsg != null) {
			IOTMessage msg = new IOTMessage();
			msg.setBytes(mqttMsg.getBytes());
			msg.setDeviceSn(getDeviceSn());
			msg.setTopic(mqttMsg.getTopic());
			return msg;
		}
		return null;
	}

	@Override
	public String getDeviceSn() {
		if(StringUtils.isBlank(deviceSn) && mqttMsg != null) {
			Matcher mat = pat.matcher(mqttMsg.getTopic());
			if(mat.find()) {
				deviceSn = mat.group(1);
			}
		}
		return deviceSn;
	}

	@Override
	public EIOTDeviceState getState() {
		return null;
	}

	@Override
	public SocketEvent getEvent() {
		return event;
	}
}
